package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.annot.CheckToken;
import com.example.demo.annot.LoginToken;
import com.example.demo.util.JwtUtil;

@RestController
@RequestMapping("/api")
public class UserController {

	@Autowired
	private UserService userService;
	
	@PostMapping("/login")
	@LoginToken
	public Object login(@RequestBody  User user ) {
		 JSONObject json = new JSONObject();
		User userForBase = userService.findUserById(user.getId());
		
		if(userForBase == null) {
			json.put("message", "登录失败，用户不存在");
			return json;
		} else {
			if (!userForBase.getPassword().equals(user.getPassword())) {
				json.put("message","登录失败，密码错误");
				return json;
			} else {
				String token = JwtUtil.createJWT(5, userForBase);
				json.put("token", token);
				json.put("user", userForBase);
				return json;
			}
		}
	}
	
	@CheckToken
	@GetMapping("/getMessage")
	public String getMessage() {
		return "你已通过验证";
	}
}
